package com.bimrun.gis.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

@Component
public class ResourceLoader {
    @Autowired
    private CesiumAssetTokenManage cesiumAssetTokenManage;

    @Autowired
    private HttpClientUtil httpClientUtil;

    @Value("${bimrun.imageResourceUrl}")
    private String imageResourceUrl;

    @Value("${bimrun.terrainResourceUrl}")
    private String terrainResourceUrl;

    @Value("${bimrun.imageResourceRootPath}")
    private String imageResourceRootPath;

    @Value("${bimrun.terrainResourceRootPath}")
    private String terrainResourceRootPath;

    public File getImageResource(String key) throws URISyntaxException, IOException {
        String filePath = imageResourceRootPath + "/" + key;
        File image = new File(filePath);
        if (!image.exists()) {
            String accessToken = cesiumAssetTokenManage.getImageToken();
            String imageUrl = imageResourceUrl.replace("{key}", key);
            image = httpClientUtil.buildRequest()
                    .buildGet(new URI(imageUrl))
                    .addHeader("Accept", "application/vnd.quantized-mesh,application/octet-stream;q=0.9,*/*;q=0.01,*/*;access_token=" + accessToken)
                    .getResponse()
                    .writeToFile(imageResourceRootPath + "/" + key);
        }
        return image;
    }

    public File getTerrainResource(String key) throws URISyntaxException, IOException {
        String fileName = terrainResourceRootPath + "/" + key;
        File terrain = new File(fileName);
        if (!terrain.exists()) {
            String accessToken = cesiumAssetTokenManage.getTerrainToken();
            String terrainUrl = terrainResourceUrl.replace("{key}", key);
            terrain = httpClientUtil.buildRequest()
                    .buildGet(new URI(terrainUrl))
                    .addHeader("Accept", "application/vnd.quantized-mesh,application/octet-stream;q=0.9,*/*;q=0.01,*/*;access_token=" + accessToken)
                    .getResponse()
                    .writeToFile(terrainResourceRootPath + "/" + key);
        }
        return terrain;
    }
}
